package com.miyake.dsp;

import java.util.ArrayList;
import java.util.List;

import org.scilab.modules.javasci.JavasciException;
import org.scilab.modules.javasci.Scilab;
import org.scilab.modules.javasci.JavasciException.InitializationException;
import org.scilab.modules.types.ScilabDouble;


public class ScilabExecute {
	private static Scilab scilab = null;
	public static synchronized ComplexArray execute(String command, ComplexArray data, String result) {
		ScilabDouble ret = null;
		try {
			if (scilab == null) {
				scilab = new Scilab();
				scilab.open();
			}
			List<ComplexArray> list = new ArrayList<ComplexArray>();
			list.add(data);
			putData(list);
			scilab.exec(command);
			ret = (ScilabDouble)scilab.get(result);
		} catch (InitializationException e) {
			e.printStackTrace();
		} catch (JavasciException e) {
			e.printStackTrace();
		}
		finally {
//			scilab.close();
		}
		
		return getReturnValue(ret);
	}

	public static synchronized ComplexArray execute(String command, ComplexArray data, ComplexArray data2, String result) {
		ScilabDouble ret = null;
		try {
			if (scilab == null) {
				scilab = new Scilab();
				scilab.open();
			}
			List<ComplexArray> list = new ArrayList<ComplexArray>();
			list.add(data);
			list.add(data2);
			putData(list);
			scilab.exec(command);
			ret = (ScilabDouble)scilab.get(result);
		} catch (InitializationException e) {
			e.printStackTrace();
		} catch (JavasciException e) {
			e.printStackTrace();
		}
		finally {
//			scilab.close();
		}
		
		return getReturnValue(ret);
	}
	
	private static ComplexArray getReturnValue(ScilabDouble ret) {
		double[] tmp = null;
		if (ret.getImaginaryPart() != null) {
			tmp = ret.getImaginaryPart()[0];
		}
		return new ComplexArray(ret.getRealPart()[0], tmp);
	}

	private static void putData(List<ComplexArray> dataList) {	
		int i = 1;
		for (ComplexArray data : dataList) {
			double[][] real = new double[1][data.getRealPart().length];
			real[0] = data.getRealPart();
			
			double[][] imag = null;
			if (data.getImagPart() != null) {
				imag = new double[1][data.getImagPart().length];
				imag[0] = data.getImagPart();
			}
			try {
				scilab.put("data" + String.valueOf(i++), new ScilabDouble(real, imag));
			} catch (JavasciException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
